/*
 * eteAccMenu - jQuery Accordion like Menu
 *
 * Copyright (c) 2010 Luca Zaccaria aka ellethee 
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://ellethee.altervista.org
 *
 */

/**
 * Version 1.0.2
*/


(function($) {
    
    var __eteMenuCount = 0;
    
    $.fn.eteAccMenu = function(options) {
        var settings = $.extend({},
        $.fn.eteAccMenu.defaults, options);
        return this.each(function() {
            var $this = $(this);
            var div = this;
            $this.addClass($.fn.eteAccMenu.defaults.menuBase);
            var oSettings = $.metadata ? $.extend({}, settings, $this.metadata()) : settings;
            if (typeof(oSettings.source) == 'object') {
                // pass
            } else if (typeof(oSettings.source == 'string')) {
                if (oSettings.source == 'ul') {
                    createFromUl(this,oSettings);
                } else {
                    //pass
                }
            }
        });
    };

    function createFromUl(what, opts) {
        $("li", what).each(function(){
            var a = $(this).children();
            
            if (a.is("a")){
                var h3 = $(a[0]).wrap('<h3>').parent();
                h3.attr("id" ,opts.baseMenuId + __eteMenuCount++);
                $(h3).hover(
                    function () {
                      $(this).addClass(opts.stateHover);
                    },
                    function () {
                      $(this).removeClass(opts.stateHover);
                    }
                );
                if (a.is("ul")){
                    $(this).attr('class',opts.headListItem);
                    h3.attr('class',opts.menuHead);
                    h3.click($.fn.eteAccMenu.fnMostra);
                    var icona = $('<span/>');
                    $(icona).attr('class',opts.headIcon);
                    $(icona).insertBefore($(a[0]));
                    $(a[1]).addClass(opts.contentList);
                    $(a[1]).hide();
                } else{
                    $(this).attr('class',opts.listItem);
                    h3.attr('class',opts.menuItem);
                }
            } else {
                alert ("I menu devono avere come primo elemento un tag <a>");
            }
        });
        var bis = _getCookie('_eteMenuSelected');
        if (bis){
            $("#"+bis).click();
        }
        
        
    };
    
    function _closeAllSibling(what){
        list = $(">li", what.parent());
        list.each(function(){
            if($(this).children().is("ul")){
                $("span.eteHeadIcon",this).attr('class',$.fn.eteAccMenu.defaults.headIcon);
                $(">h3",this).attr('class',$.fn.eteAccMenu.defaults.menuHead);
                $(">ul",this).hide("fast");
            }
        });
    };
    
    $.fn.eteAccMenu.fnMostra = function(evento) {
        evento.stopPropagation();
        _closeAllSibling($(this).parent());
        var target = $(">ul", $(this).parent());
        if (target.length) {
            _setCookie("_eteMenuSelected",$(this).attr('id'),null);
            var i = $("span.eteHeadIcon",this)[0];
            $(this).addClass($.fn.eteAccMenu.defaults.stateSelected);
            target = target[0];
            if ($(target).is(":hidden")) {
                $(i).toggleClass($.fn.eteAccMenu.defaults.headSelIcon,true);
                $(target).show('fast');
                
            } else {
                $(i).toggleClass($.fn.eteAccMenu.defaults.headSelIcon,false);
                $(target).hide('fast');
            }
        }
    };


    function _setCookie(nome, valore, scadenza) {
        if (!scadenza) {
            var oggi = new Date();
            oggi.setMonth(oggi.getMonth() + 3);
            //restituisce la data nel formato necessario
            scadenza = oggi.toGMTString();
        }
        valore = escape(valore);
        document.cookie = nome + "=" + valore + ";expires=" + scadenza;
    };

    function _getCookie(nome) {
        var valore = document.cookie; 
        var inizioCookie = valore.indexOf(" " + nome + "=");
        if (inizioCookie == -1) {
            inizioCookie = valore.indexOf(nome + "=");
        }
        if (inizioCookie == -1) {
            valore = null;
        }
        if (inizioCookie >= 0) {
            inizioCookie = valore.indexOf("=", inizioCookie) + 1;
            var fineCookie = valore.indexOf(";", inizioCookie);
            if (fineCookie == -1){
                fineCookie = valore.length;
            }
            valore = unescape(valore.substring(inizioCookie, fineCookie));
        }
        return valore;
    };



    /* defaults */
    $.fn.eteAccMenu.defaults = {
        // set the constructor type 
        source          : 'ul',
        useUI           : true,
        menuHead        : 'eteMenuHead eteStatenormal ui-accordion-header ui-helper-reset ui-state-default ui-corner-all',
        listItem        : 'eteListItem',
        headListItem    : 'eteHeadListItem',
        contentList     : 'eteContentList ui-corner-bottom ui-accordion-content-active',
        menuBase        : 'eteMenuBase ui-accordion ui-widget ui-helper-reset',
        menuItem        : 'eteMenuItem ui-accordion-header ui-helper-reset ui-state-default ui-corner-all',
        headIcon        : 'eteHeadIcon eteHeadIcon-closed ui-icon ui-icon-triangle-1-e',
        headNormalIcon  : 'eteHeadIcon-closed ui-icon-triangle-1-e',
        headSelIcon     : 'eteHeadIcon-opened ui-icon-triangle-1-s',
        stateNormal     : 'eteStatenormal ui-corner-all',
        stateSelected   : 'eteStateSelected ui-corner-top',
        stateHover      : 'eteStateHover ui-state-hover',
        baseMenuId      : 'eteMenuId_'
    };

})(jQuery);